import React, { Component } from 'react'
import logo from '@/assets/logo.png'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import styles from './index.module.scss'
import { reqLogin } from '@/api/user'
import { setToken } from '@/utils/storage'

export default class Login extends Component {
  state = {
    isLogin: false,
  }
  render() {
    // console.log(this.props, 1313)
    return (
      <div className={styles.login}>
        <Card className="login-container">
          <img className="login-logo" src={logo} alt="" />

          <Form
            name="basic"
            autoComplete="off"
            size="large"
            onFinish={this.onFinish}
            initialValues={{
              mobile: '13811111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '手机格式不正确',
                },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入6位验证码 ' },
                {
                  len: 6,
                  message: '请输入6位验证码',
                },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              rules={[
                {
                  validator: (_, value) => {
                    if (value === true) {
                      return Promise.resolve()
                    } else {
                      return Promise.reject(new Error('请同意用户许可'))
                    }
                  },
                },
              ]}
              valuePropName="checked"
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  onFinish = async ({ mobile, code }) => {
    // console.log(values)

    if (!this.state.isLogin) {
      this.setState({
        isLogin: true,
      })
      try {
        const {
          data: { token },
        } = await reqLogin(mobile, code)

        //将token存到本地
        setToken(token)

        message.success('登录成功', 2, () => {
          this.setState({
            isLogin: false,
          })
          //跳转到首页。看有没有传回跳地址  ？.
          const pathname = this.props.location?.state?.pathname
          this.props.history.push(pathname || '/home')
        })
      } catch (e) {
        message.error(e.response.data.message, 2)
        this.setState({
          isLogin: false,
        })
      }
    }
  }
}
